const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    wordLists: ['基础词汇', '中级词汇', '高级词汇'], // 词库选择列表
    selectedWordList: '基础词汇', // 默认选择基础词汇
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    learnedCount: 0, // 已学习单词数
    dailyGoal: 10, // 用户的每日学习计划，默认是10个单词
    uniqueId: '', // 用户的唯一标识符
    showDailyGoalInput: false // 控制每日学习目标输入框的模态窗口显示
  },

  onLoad: function () {
    this.loadUserData(); // 加载用户数据，包括用户信息、学习进度、每日目标等
  },

  viewFavorites: function() {
    // 跳转到收藏页面
    wx.navigateTo({
      url: '/packageE/pages/favourword/favourword'
    });
  },

  viewgames: function() {
    // 跳转到收藏页面
    wx.navigateTo({
      url: '/packageE/pages/wordgame/wordgame'
    });
  },

  // 加载用户数据的方法，封装用户信息、学习进度的加载逻辑
  loadUserData: function (callback) {
    // 获取或生成唯一用户标识符
    let uniqueId = wx.getStorageSync('uniqueId');
    if (!uniqueId) {
      // 如果本地没有存储 uniqueId，则生成一个新的 UUID 并存储
      uniqueId = generateUUID();
      wx.setStorageSync('uniqueId', uniqueId);
    }
    this.setData({
      uniqueId: uniqueId
    });

    // 获取用户存储的 dailyGoal
    let storedDailyGoal = wx.getStorageSync('dailyGoal');
    if (storedDailyGoal) {
      this.setData({
        dailyGoal: storedDailyGoal
      });
    }

    // 获取用户存储的 userInfo
    let storedUserInfo = wx.getStorageSync('userInfo');
    if (storedUserInfo) {
      this.setData({
        userInfo: storedUserInfo,
        hasUserInfo: true
      });
    }

    // 获取学习进度
    this.getLearningProgress();

    // 执行回调函数（如存在），例如停止刷新动画
    if (typeof callback === 'function') {
      callback();
    }
  },

  // 下拉刷新触发的回调函数
  onPullDownRefresh: function () {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();

    // 重新加载用户数据，包括学习进度和每日目标等
    this.loadUserData(() => {
      // 停止下拉刷新动画和顶部加载动画
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
    });
  },

  /*bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },*/

  // 显示每日学习目标的模态窗口
  showDailyGoalModal: function () {
    this.setData({
      showDailyGoalInput: true
    });
  },

  // 关闭每日学习目标的模态窗口
  closeDailyGoalModal: function () {
    this.setData({
      showDailyGoalInput: false
    });
  },

  // 确认每日学习目标的输入
  confirmDailyGoal: function () {
    this.setData({
      showDailyGoalInput: false
    });

    // 保存新的目标到本地存储
    wx.setStorageSync('dailyGoal', this.data.dailyGoal);
  },

  // 用户输入新的每日学习目标时的回调
  onDailyGoalChange: function (e) {
    const newGoal = parseInt(e.detail.value);
    if (!isNaN(newGoal) && newGoal > 0) {
      this.setData({
        dailyGoal: newGoal
      });
    }
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
    // 保存头像到本地存储
    wx.setStorageSync('userInfo', this.data.userInfo);
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
    // 保存昵称到本地存储
    wx.setStorageSync('userInfo', this.data.userInfo);
  },

  // 清空已学习单词数的方法
clearLearnedWords() {
  const uniqueId = this.data.uniqueId;
  const progressKey = `learningProgress_${uniqueId}`;

  // 清空学习进度的本地存储数据
  const newProgress = {
    learnedWords: [],
    learnedCount: 0
  };
  wx.setStorageSync(progressKey, newProgress);

  // 更新页面数据
  this.setData({
    learnedCount: 0
  });

  // 显示提示
  wx.showToast({
    title: '已清空学习记录',
    icon: 'success',
    duration: 1500
  });
},


  GetUserProfile: function () {
    wx.getUserProfile({
      desc: '用于个性化记录学习数据',
      success: (res) => {
        console.log(res);
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
        wx.setStorageSync('userInfo', res.userInfo);
        this.getLearningProgress();
      },
      fail: (err) => {
        console.error("用户拒绝授权", err);
      }
    });
  },

  onWordListChange: function (e) {
    this.setData({
      selectedWordList: this.data.wordLists[e.detail.value]
    });
  },

  startLearning: function () {
    wx.setStorageSync('selectedWordList', this.data.selectedWordList);
    wx.navigateTo({
      url: '/packageE/pages/word/word'
    });
  },

  onDailyGoalChange: function (e) {
    const newGoal = parseInt(e.detail.value);
    if (!isNaN(newGoal) && newGoal > 0) {
      this.setData({
        dailyGoal: newGoal
      });
      wx.setStorageSync('dailyGoal', newGoal);
    } else {
      wx.showToast({
        title: '请输入有效的每日学习目标',
        icon: 'none',
        duration: 2000
      });
    }
  },

  getLearningProgress: function () {
    const uniqueId = this.data.uniqueId;
    const progressKey = `learningProgress_${uniqueId}`;
    const learningProgress = wx.getStorageSync(progressKey) || {
      learnedWords: [],
      learnedCount: 0
    };

    this.setData({
      learnedCount: learningProgress.learnedWords.length
    });
  }

});

function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
